import {
  Component,
  Input,
  Output,
  EventEmitter,
  OnInit,
  OnChanges
} from "@angular/core";
import { NzNotificationService } from "ng-zorro-antd";
import { Router } from "@angular/router";
import { HttpServcie } from "../../../../service/http.service";
import { Config } from "../../../../service/config";
import { el } from "@angular/platform-browser/testing/src/browser_util";
import {
  FormBuilder,
  FormGroup,
  Validators,
  FormControl
} from "@angular/forms";
import { InformationBean } from "../bean/information.bean";
import { FileUploader, FileItem, ParsedResponseHeaders } from "ng2-file-upload";
@Component({
  selector: "information-modify",
  templateUrl: "information-modify.html",
  styleUrls: ["information-modify.scss"]
})
export class InformationModifyPage implements OnInit, OnChanges {
  validateForm: FormGroup;
  isSpinning: boolean = false;
  showImage: any = [];
  config = Config;
  owner: any = false;
  sysUser: any = JSON.parse(window.localStorage.getItem("user"));
  fileUploader = new FileUploader({
    url: Config.IP + Config.API.upload,
    method: "POST",
    itemAlias: "file",
    autoUpload: false,
    headers: [
      { name: "Authorization", value: "Bearer " + window.localStorage["token"] }
    ]
  });
  @Input() inValue: any = [];
  @Output("outPut") outPut = new EventEmitter();
  editorValue: any = "";
  informationBean: InformationBean = new InformationBean();
  constructor(
    private fb: FormBuilder,
    private httpServcie: HttpServcie,
    private _notification: NzNotificationService
  ) { }
  ngOnInit() {
    this.validateForm = this.fb.group({
      title: [null, [Validators.required]],
      subTitle: [null, [Validators.required]]
    });
  }
  ngOnChanges() {
    if (this.inValue) {
      this.informationBean = Object.assign({}, this.inValue);
      if (this.informationBean.fileUrls) {
        this.showImage = this.informationBean.fileUrls.split(",");
      }
      if (this.informationBean.content) {
        this.informationBean.content = decodeURIComponent(
          atob(this.informationBean.content)
        );
      }
    }

    if (this.informationBean.createPartyId == this.sysUser.partyId) {
      this.owner = true;
    }
  }

  //交验
  getFormControl(name) {
    //return this.validateForm.controls[name];
  }

  doUpdate($event) {
    this.isSpinning = true;
    this.informationBean.fileUrls = this.showImage.join(",");
    this.informationBean.content = btoa(
      encodeURIComponent(this.informationBean.content)
    );
    this.httpServcie.updateInformation(this.informationBean).subscribe(data => {
      this.isSpinning = false;
      if (data.status == 200) {
        this._notification.create("success", "成功提示", "修改成功");
        this.outPut.emit($event);
      } else {
        this._notification.create("error", "失败提示", data.message);
        return;
      }
    });
  }

  //选择文件后调用的方法
  selectedFileOnChanged(event) {
    if (event.target.files[0].type.match("image.*")) {
      //手动上传的
      this.fileUploader.uploadAll();
      this.fileUploader.onSuccessItem = (
        item: FileItem,
        response: string,
        status: number,
        headers: ParsedResponseHeaders
      ) => {
        if (status == 200) {
          //判断是否是图片
          if (item.file.type.match("image.*")) {
            this.showImage.push(JSON.parse(response).data);
            //this.userBean.qualificationsUrl = JSON.parse(response).data;
          } else {
            this._notification.create("warning", "警告提示", "请选择图片类型！");
          }
        }
      };
    } else {
      this.fileUploader.clearQueue();
      this._notification.create("warning", "警告提示", "请选择图片类型！");
    }
  }

  delete(param) {
    if (this.informationBean.createPartyId == this.sysUser.partyId) {
      this.httpServcie.removeByValue(this.showImage, param);
      // this.httpServcie.deleteUpload(param).subscribe(data=>{
      //     if(data.status==200){
      //         this.httpServcie.removeByValue(this.showImage,param);
      //         //this._notification.create('success', '成功提示', '移除成功');
      //     }else{
      //         //this._notification.create('error', '失败提示', data.message);
      //         return;
      //     }
      // },error=>{

      // });
    }
  }

  download1(url, name) {
    let name1 = name + "." + url.split(".")[1];
    this.download(url, name1);
  }
  download(url, name) {
    let link = document.createElement("a");
    let body = document.querySelector("body");

    this.getBlob(Config.IP + Config.API.getUpload + url).then(blob => {
      link.href = window.URL.createObjectURL(blob);
      link.download = name;
      // fix Firefox
      link.style.display = "none";
      body.appendChild(link);
      link.click();
      body.removeChild(link);
      window.URL.revokeObjectURL(link.href);
    });
  }

  getBlob(url) {
    return new Promise(resolve => {
      const xhr = new XMLHttpRequest();
      xhr.open("GET", url, true);
      xhr.responseType = "blob";
      xhr.onload = () => {
        if (xhr.status === 200) {
          resolve(xhr.response);
        }
      };
      xhr.send();
    });
  }

  openDocs(url) {
    let list: Array<string> = [
      "doc",
      "dot",
      "docx",
      "dotx",
      "docm",
      "dotm",
      "xls",
      "xlt",
      "xla",
      "xlsx",
      "xltx",
      "xlsm",
      "xltm",
      "xlam",
      "xlsb",
      "ppt",
      "pot",
      "pps",
      "ppa",
      "pptx",
      "potx",
      "ppsx",
      "ppam",
      "pptm",
      "potm",
      "ppsm"
    ];
    let lookUrl = "";
    let tt = url.split(".");
    let houzui = null;
    if (tt.length > 1) {
      houzui = tt[tt.length - 1];
    }
    if (houzui) {
      if (list.indexOf(houzui) >= 0) {
        lookUrl = Config.OFFICE_URL + Config.PREVIEW_URL + url;
      } else {
        lookUrl = Config.PREVIEW_URL + url;
      }
    } else {
      lookUrl = Config.PREVIEW_URL + url;
    }

    window.open(lookUrl, "_blank");
  }
}
